

/**
 * @ClassName Offer58
 * @Description 剑指 Offer 58 - I. 翻转单词顺序
 * @Author clockTown
 * @Date 2021/8/24 13:49
 * @Version 1.0
 */
class Offer58 {
}

/**
 * v0 正则
 */
class Offer58V0 {
    public String reverseWords(String s) {
        s = s.trim();
        String[] split = s.split("\\s+");
        StringBuilder sb = new StringBuilder();
        for (int i = split.length - 1; i >= 0; i--) {
            sb.append(split[i]);
            if (i > 0){
                sb.append(" ");
            }
        }
        return sb.toString();
    }
}

/**
 * v1 双指针
 */
class Offer58V1 {
    public String reverseWords(String s) {
        // 删除首尾空格
        s = s.trim();
        int slow = s.length() - 1, fast = slow;
        StringBuilder res = new StringBuilder();
        while(fast >= 0) {
            // 搜索首个空格
            while(fast >= 0 && s.charAt(fast) != ' ') {
                fast--;
            }
            // 添加单词
            res.append(s.substring(fast + 1, slow + 1) + " ");
            // 跳过单词间空格
            while(fast >= 0 && s.charAt(fast) == ' ') {
                fast--;
            }
            // slow 指向下个单词的尾字符
            slow = fast;
        }
        // 转化为字符串并返回
        return res.toString().trim();
    }
}


